//IIFE：立即执行函数
(function () {
    document.write("IIFE<br>");
})();

(function (a, b) {
    let sum = a + b;
    document.write(`${sum}<br>`);
})(1, 2);

var num1 = 20, num2 = 30, sum = 0;
//全局函数可以访问全局变量
function add() {
    return num1 + num2;
}
sum = add();
document.write(`${sum}<br>`);

//嵌套函数
function getScore() {
    var num1 = 2, num2 = 3;

    //内部嵌套函数
    function add2() {
        return num1 + num2;
    }
    return add2();
}
// document.write(`${add2()}<br>`);  //无法访问嵌套的内部函数
document.write(`${getScore()}<br>`);

var x1 = "全局变量：容器函数之外的变量";
var demo = (function (name) {
    var len = name.length;
    return function () {
        document.write(`内部函数可以访问容器函数的变量：${len}<br>`);
        document.write(`内部函数可以访问全局变量：${x1}<br>`);
        return name;
    }
})("张三")
//执行
demo();

//闭包：计数器功能
//全局变量  计数器counter不安全
var counter1 = 0;  
function add3() {
    return counter1 += 1;
}
document.write(`${add3()}<br>`);
document.write(`${add3()}<br>`);
document.write(`${add3()}<br>`);
counter1 = 6;//外部可以随意修改
document.write(`${add3()}<br>`);

//局部变量：函数内部变量，无法实现计数功能
function add4() {
    var counter2 = 0;
    return (counter2 += 1);
}
document.write(`${add4()}<br>`);
document.write(`${add4()}<br>`);
document.write(`${add4()}<br>`);

//闭包
var add5 = (function () {
    var counter3 = 0;
    return function () {
        return (counter3 += 1);
    }
})();
document.write(`${add5()}<br>`);
document.write(`${add5()}<br>`);
document.write(`${add5()}<br>`);
counter3 = 5;  //定义了一个全局变量counter3，与add5函数内部的counter3无关
document.write(`${add5()}<br>`);